package com.muyu.filter;

import com.muyu.body.BodyReaderHttpServletRequestWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @ClassName: HttpServletRequestReplacedFilter
 * @Author: Zirun.Xin
 * @Date: 2025/3/21 下午4:06
 * @Version: 1.0
 * @Description: 请求体处理过滤器，仅处理application/json类型的请求
 */
@Slf4j
@Component
@Order(value = 0)
@WebFilter(filterName = "httpServletRequestReplacedFilter", urlPatterns = "/*")
public class HttpServletRequestReplacedFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        log.info("进入HttpServletRequestReplacedFilter");

        // 检查请求是否是HttpServletRequest类型
        if (request instanceof HttpServletRequest) {
            HttpServletRequest httpRequest = (HttpServletRequest) request;

            // 获取请求的Content-Type
            String contentType = httpRequest.getContentType();
            log.info("请求的Content-Type: {}", contentType);

            // 仅处理application/json类型的请求
            if (contentType != null && contentType.toLowerCase().contains("application/json")) {
                log.info("请求是application/json类型，执行过滤逻辑");
                ServletRequest requestWrapper = new BodyReaderHttpServletRequestWrapper(httpRequest);
                chain.doFilter(requestWrapper, response);
                return; // 结束当前过滤器的执行
            } else {
                log.info("请求不是application/json类型，直接放行");
            }
        }

        // 非application/json类型的请求，直接放行
        chain.doFilter(request, response);
    }
}
